package com.uminho.egendme;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import com.uminho.exceptions.DestroyException;
import com.uminho.exceptions.InvalidOAuthParametersError;
import com.uminho.exceptions.InvalidOAuthTokenError;
import com.uminho.exceptions.NotAllowedError;
import com.uminho.exceptions.OAuthServiceFailureError;
import com.uminho.exceptions.SaveException;
import com.uminho.http.Webservice;
import com.uminho.objects.Appointment;
import com.uminho.objects.SimpleAppointment;
import com.uminho.objects.Task;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ExchangeDialog extends Dialog {

	private SimpleAppointment request;
	private Appointment owned;
	private Long exchangeId;
	private boolean acceptable;
	Context context;
	Handler handler;

	public ExchangeDialog(Context context, Appointment owned,
			SimpleAppointment request, Long exchangeId) {
		this(context, owned, request, exchangeId, true);
	}

	public ExchangeDialog(Context context, Appointment owned,
			SimpleAppointment request, Long exchangeId, boolean acceptable) {
		super(context, R.style.WindowTitleBackground);

		this.owned = owned;
		this.request = request;
		this.exchangeId = exchangeId;
		this.acceptable = acceptable;
		this.context = context;
	}

	private String getString(int id){
		return getContext().getString(id);
	}

	@Override
	protected void onStart() {
		super.onStart();

		requestWindowFeature(Window.FEATURE_NO_TITLE); // Hides Title
		setContentView(R.layout.exchange_request);
		
		
		TextView title = (TextView) findViewById(R.id.title);
		if(acceptable)
			title.setText(R.string.exchangeTitle);
		else
			title.setText(R.string.exchangeDetailsTitle);

		/* Set Fixed Views */
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH'h'mm'm'");
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

		TextView ownedDate = (TextView) findViewById(R.id.ownedDate);
		TextView requestDate = (TextView) findViewById(R.id.requestDate);
		TextView ownedTime = (TextView) findViewById(R.id.ownedTime);
		TextView requestTime = (TextView) findViewById(R.id.requestTime);

		ownedDate.setText(dateFormat.format(owned.getStartDate().getTime()));
		requestDate
		.setText(dateFormat.format(request.getStartDate().getTime()));
		ownedTime.setText(timeFormat.format(owned.getStartDate().getTime()));
		requestTime
		.setText(timeFormat.format(request.getStartDate().getTime()));

		/* Set views programmatically */
		ViewGroup ownedPanel = (ViewGroup) findViewById(R.id.ownedPanel);
		ViewGroup requestPanel = (ViewGroup) findViewById(R.id.requestPanel);
		ViewGroup infoPanel = (ViewGroup) findViewById(R.id.infoPanel);

		addField(infoPanel, getString(R.string.name), owned.getService().getTitle());

		String[] categories = getContext().getResources().getStringArray(
				R.array.categorieslist);
		addField(infoPanel, getString(R.string.category), categories[owned.getService()
		                                                             .getCategory_id().intValue()]);

		for (Task t : owned.getTasks()) {
			addField(infoPanel, getString(R.string.taskName), t.getName());
			addDescriptiveField(infoPanel, getString(R.string.taskDescription),
					t.getDescription());
		}

		addDescriptiveField(infoPanel, getString(R.string.comment), owned.getComment());

		setOnClickListeners();

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				
				//OK
				if(msg.what==1){
					Toast.makeText(context,R.string.operationconfirmed, Toast.LENGTH_LONG).show();	
				}else if(msg.what==-1){
					Toast.makeText(context,R.string.unknownerrorinternetconnection, Toast.LENGTH_LONG).show();	
				}else if (msg.what==0){
					Toast.makeText(context,R.string.notallowed, Toast.LENGTH_LONG).show();	
				}
				
			}};
	}

	private void addDescriptiveField(ViewGroup parent, String label,
			String value) {
		if (value == null || value.length() == 0)
			return;

		View v = LayoutInflater.from(getContext()).inflate(
				R.layout.dialogdfield, parent, false);

		TextView textView = (TextView) v.findViewById(R.id.label);
		textView.setText(label + " ");
		textView = (TextView) v.findViewById(R.id.value);
		textView.setText(value);

		parent.addView(v);
	}

	private void addField(ViewGroup parent, String label, String value) {
		addField(parent, label, value, null);
	}

	private void addField(ViewGroup parent, String label, String value,
			Integer link) {
		if (value == null || value.length() == 0)
			return;

		View v = LayoutInflater.from(getContext()).inflate(
				R.layout.dialogfield, parent, false);

		TextView textView = (TextView) v.findViewById(R.id.label);
		textView.setText(label + " ");
		textView = (TextView) v.findViewById(R.id.value);
		textView.setText(value);
		if (link != null)
			textView.setAutoLinkMask(link);

		parent.addView(v);
	}

	private void setOnClickListeners() {
		View buttonsAcceptable = findViewById(R.id.buttonsAcceptable);
		View buttonsNotAcceptable = findViewById(R.id.buttonsNotAcceptable);

		if (acceptable) {

			buttonsAcceptable.setVisibility(View.VISIBLE);
			buttonsNotAcceptable.setVisibility(View.GONE);

			Button accept = (Button) findViewById(R.id.accept);
			Button reject = (Button) findViewById(R.id.reject);

			accept.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					new Thread() {
						@Override
						public void run() {
							Webservice w = Webservice.getInstance();
							try {
								try {
									Log.d("exchange", "accepted");
									w.answerExchanges(exchangeId, true);
									handler.sendEmptyMessage(1);
								} catch (ClientProtocolException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (IOException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (JSONException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (InvalidOAuthParametersError e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (InvalidOAuthTokenError e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (OAuthServiceFailureError e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (NotAllowedError e) {
									handler.sendEmptyMessage(0);
									e.printStackTrace();
								} catch (SaveException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (DestroyException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								}

							} catch (URISyntaxException e) {
								handler.sendEmptyMessage(-1);
								e.printStackTrace();
							}
						}
					}.start();

					dismiss();
				}
			});

			reject.setOnClickListener(new View.OnClickListener() {


				public void onClick(View v) {
					new Thread() {
						@Override
						public void run() {
							Webservice w = Webservice.getInstance();
							try {
								try {
									Log.d("exchange", "rejected");
									w.answerExchanges(exchangeId, false);
									handler.sendEmptyMessage(1);
								} catch (ClientProtocolException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (IOException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (JSONException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (InvalidOAuthParametersError e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (InvalidOAuthTokenError e) {
									handler.sendEmptyMessage(0);
									e.printStackTrace();
								} catch (OAuthServiceFailureError e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (NotAllowedError e) {
									Toast.makeText(context,R.string.notallowed, Toast.LENGTH_LONG).show();	
									e.printStackTrace();
								} catch (SaveException e) {
									handler.sendEmptyMessage(-1);
									e.printStackTrace();
								} catch (DestroyException e) {
									handler.sendEmptyMessage(-1);	
									e.printStackTrace();
								}

							} catch (URISyntaxException e) {
								handler.sendEmptyMessage(-1);
								e.printStackTrace();
							}
						}
					}.start();


					dismiss();
				}
			});
		}
		else{
			buttonsAcceptable.setVisibility(View.GONE);
			buttonsNotAcceptable.setVisibility(View.VISIBLE);

			Button dismiss = (Button) findViewById(R.id.dismiss);

			dismiss.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dismiss();

				}
			});
		}
	}

}
